package chen.web.email;

import java.io.UnsupportedEncodingException;

import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 支持email地址形如：张三<xx@xx.com> 或者 xx@xx.com
 * @author chen
 *
 */
public class EmailAddress {

	public static final String Regex = "";
	
	private String address;
	private String hostName;
	private String userName;
	
	private static Log log = LogFactory.getLog(EmailAddress.class);

	public EmailAddress(String email){
		int length = email.length();
		if(length == 0){
			throw new IllegalArgumentException();
		}
		if(email.lastIndexOf('>') == length -1){
			int splitIndex = email.lastIndexOf('<');
			address = email.substring(splitIndex+1, length-1);
			userName = email.substring(0, splitIndex);
		} else {
			this.address = email;
		}
		hostName = address.split("@")[1];
	}
	
	public String getAddress(){
		return address;
	}
	
	public String getHostName(){
		return hostName;
	}
	
	public String getUserName(){
		return userName;
	}
	
	/**
	 * 如果email地址形如：张三<xx@xx.com>，直接发送会有中文乱码现象。
	 * 此方法会将email前面的姓名用Base64编码，可正常显示中文
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String encode(){
		if(userName != null){
			String base64Str;
			try {
				base64Str = MimeUtility.encodeText(userName, "UTF-8", "B");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				//出错后直接返回简单地址形式
				log.error(e);
				return address;
			}
			StringBuilder sb = new StringBuilder();
			sb.append(base64Str)
			  .append("<")
			  .append(address)
			  .append(">");	
			return sb.toString();
		}
		return address;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result
				+ ((userName == null) ? 0 : userName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		EmailAddress other = (EmailAddress) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (userName == null) {
			if (other.userName != null)
				return false;
		} else if (!userName.equals(other.userName))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return getAddress();
	}

}
